package com.user.profile.service.label;

import com.user.profile.enums.OperateEnum;
import com.user.profile.perm.ClickHousePerm;
import com.user.profile.request.SaveLabelRequest;
import com.user.profile.request.SaveLabelRequest.UserInfo;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javafx.util.Pair;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @Author linlx
 * @Date 2021/9/18 9:34
 * @Description
 **/
@Service
public class UserBehaviorCkBuildImpl extends AbstractCkBuildService {

  @Resource
  private CommonHelper commonHelper;

  @Override
  public Pair<StringBuilder, Map<Integer, UserInfo>> buildAllOperate(SaveLabelRequest request) {
    // 拼接主子标签的关联关系
    return commonHelper.buildAllOperate(request.getUserBehaviorData());
  }

  @Override
  public String buildCkSQL(Pair<StringBuilder, Map<Integer, UserInfo>> pair,
      Integer parentOperate) {
    // 没有用户行为标签
    if (null == pair) {
      return StringUtils.EMPTY;
    }
    StringBuilder operateBuilder = pair.getKey();
    Map<Integer, UserInfo> allMap = pair.getValue();

    // 单标签
    if (null == parentOperate) {
      operateBuilder = new StringBuilder("bitmapToArray(").append(operateBuilder).append(")");
    }

    StringBuilder result = new StringBuilder("SELECT ");
    result.append(operateBuilder.toString()).append(" AS user_number2, 1 AS BID ");
    Set<Entry<Integer, UserInfo>> sonEntries = allMap.entrySet();
    int setIndex = 0;
    for (Entry<Integer, UserInfo> entry : sonEntries) {
      StringBuilder ckSql = new StringBuilder(ClickHousePerm.SELECT_SON);
      if (setIndex == 0) {
        this.buildFirst(result, sonEntries, setIndex, entry, ckSql);
      } else {
        this.buildOther(result, sonEntries, setIndex, entry, ckSql);
      }
      setIndex++;
    }
    System.out.println(result.toString());
    return result.toString();
  }

  private void buildFirst(StringBuilder result, Set<Entry<Integer, UserInfo>> sonEntries,
      int setIndex, Entry<Integer, UserInfo> entry, StringBuilder ckSql) {
    UserInfo attributesInfo = entry.getValue();
    String[] timeArr = attributesInfo.getKey().split("至");
    // 没有总次数的情况
    if (StringUtils.isEmpty(attributesInfo.getTarget())) {
      // 第一次拼接不存在子条件，所以都是带有时间参数的父标签
      result.append("FROM (");
      ckSql.append("user").append(entry.getKey()).append(" FROM");
      ckSql.append(" ch_label_date where (");
      ckSql.append("labelname = ").append("'").append(attributesInfo.getValue()).append("'")
          .append(" and (")
          .append("labelvalue >").append("'").append(timeArr[0]).append("'")
          .append(" and ").append("labelvalue <=").append("'").append(timeArr[1]).append("'")
          .append(")")
          .append(")");
    } else {
      result.append("FROM (");
      ckSql.append("user").append(entry.getKey()).append(" FROM(");
      ckSql.append(" SELECT user_ids, sum(count) AS SCOUNT").append(setIndex)
          .append(" FROM ch_label_date where( ")
          .append("labelname = ").append("'").append(attributesInfo.getValue()).append("'")
          .append(" and")
          .append("(labelvalue >").append("'").append(timeArr[0]).append("'")
          .append(" and ").append("labelvalue <=").append("'").append(timeArr[1]).append("'")
          .append(")")
          .append(")")
          .append("GROUP BY (user_ids)")
          .append(") where ").append("SCOUNT").append(setIndex)
          .append(OperateEnum.get(attributesInfo.getCountOperate()).getName())
          .append(attributesInfo.getCount());
    }
    if (sonEntries.size() > 1) {
      ckSql.append(") ").append("a").append(setIndex).append(" ");
    } else {
      ckSql.append(") ");
    }
    result.append(ckSql.toString());
    System.out.println("ckSql ==============" + ckSql.toString());
  }

  private void buildOther(StringBuilder result, Set<Entry<Integer, UserInfo>> sonEntries,
      int setIndex, Entry<Integer, UserInfo> entry, StringBuilder ckSql) {
    UserInfo attributesInfo = entry.getValue();
    String time = attributesInfo.getKey();
    // 没有时间的则为子条件
    if (StringUtils.isEmpty(time)) {
      if ("启动时长".equals(attributesInfo.getTarget())
          || "IP".equals(attributesInfo.getTarget())) {
        result.append("INNER JOIN (");
        ckSql.append("user").append(entry.getKey()).append(" FROM");
        ckSql.append(" ch_label_string where (");
        ckSql.append("labelname = ").append("'").append(attributesInfo.getTarget())
            .append("'")
            .append(" and ")
            .append("labelvalue")
            .append(OperateEnum.get(attributesInfo.getCountOperate()).getName())
            .append("'")
            .append(attributesInfo.getCount())
            .append("'")
            .append(")");
        result.append(ckSql);
        result.append(") ").append("a").append(setIndex).append(" ");
      }
    } else {
      // 有时间的
      if (StringUtils.isEmpty(attributesInfo.getTarget())) {
        // 没有总次数
        String[] timeArr = time.split("至");
        result.append("INNER JOIN (");
        ckSql.append("user").append(entry.getKey()).append(" FROM");
        ckSql.append(" ch_label_date where (");
        ckSql.append("labelname = ").append("'").append(attributesInfo.getValue()).append("'")
            .append(" and (")
            .append("labelvalue >").append("'").append(timeArr[0]).append("'")
            .append(" and ").append("labelvalue <=").append("'").append(timeArr[1]).append("'")
            .append(")")
            .append(")");
        result.append(ckSql.toString());
        result.append(") ").append("a").append(setIndex);
      } else {
        String[] timeArr = time.split("至");
        result.append("INNER JOIN (");
        ckSql.append("user").append(entry.getKey()).append(" FROM(");
        ckSql.append(" SELECT user_ids, sum(count) AS SCOUNT").append(setIndex)
            .append(" FROM ch_label_date where( ")
            .append("labelname = ").append("'").append(attributesInfo.getValue()).append("'")
            .append(" and")
            .append("(labelvalue >").append("'").append(timeArr[0]).append("'")
            .append(" and ").append("labelvalue <=").append("'").append(timeArr[1]).append("'")
            .append(")")
            .append(")")
            .append("GROUP BY (user_ids)")
            .append(") where ").append("SCOUNT").append(setIndex)
            .append(OperateEnum.get(attributesInfo.getCountOperate()).getName())
            .append(attributesInfo.getCount());
        result.append(ckSql);
        result.append(") ").append("a").append(setIndex);
      }
    }
    if (sonEntries.size() > 1) {
      result.append(" ON ").append("a").append(setIndex - 1).append(".").append("join_id")
          .append("=")
          .append("a").append(setIndex).append(".").append("join_id ");
    } else {
      result.append(") ");
    }
  }


}
